from __future__ import absolute_import, unicode_literals
import json
from Crypto.Cipher import AES
import base64


class WXBizDataCrypt:
    def __init__(self, appId, sessionKey):
        self.appId = appId
        self.sessionKey = sessionKey

    def decrypt(self, encryptedData, iv):
        # base64 decode
        sessionKey = base64.b64decode(self.sessionKey)
        encryptedData = base64.b64decode(encryptedData)
        iv = base64.b64decode(iv)

        cipher = AES.new(sessionKey, AES.MODE_CBC, iv)

        decrypted = json.loads(self._unpad(cipher.decrypt(encryptedData)))

        if decrypted['watermark']['appid'] != self.appId:
            raise Exception('Invalid Buffer')

        return decrypted

    def _unpad(self, s):
        return s[:-ord(s[len(s) - 1:])]


def main():
    appId = 'wx96689acabe0ef814'
    sessionKey = 'k+a4uTJF8FKughx8hwofrA=='
    encryptedData = 'BoPZSkgn/B/ZLwHpdUqfz6HpN0mBjmjUvZ5ThLqod0LiE+XF6QwWcFq79F1th71gtcxkfMzfzC7Oo0xK/fYCGjamC3dnjFMqkzX5cqNWQr5rHU2yJZ/3HUHcOYmot2loty+55YDmr5QkQR73yyYMART3hcc//YJl/MHlM+T4L5k9oJ/vDnxllhYBXoZ3fULg2MH9eiU4H1/QpgeKeM7rew=='
    iv = '7p+36eAjpAESWPG/TEeKMw=='

    # sessionKey = 'k+a4uTJF8FKughx8hwofrA=='
    # encryptedData = 'OtIl3eW9onkMgcKYbDCOC1yJixlid2Dk2xHNp/Fx95oQPmkb0sRO2TVtToJHXXH9uN8wbOOBHuXGr3l3YJZqpgsnLcbP3HvriNtl+Seu+2jgmx/58KwEyazYG82jGT4a5UdlL+hJbYnoul8k2t/znKhi+SDCeSFlfqF2bibj2N+frsXTDtJ7Tgorf7ZmFO/HdUVJhiOyPCkAK6QSHmRDyA=='
    # iv = 'gYWgvep6YO0he2qkWHbemA=='

    # iv = "4ryjmKfp80qjBPkgdE/SIQ=="
    # sessionKey = "k+a4uTJF8FKughx8hwofrA=="
    # encryptedData = "NYTyXWKdokXwzWUT6U6+eQOIIiVTJJR8qGIqtxu2xhvd482suxoDwZDm4uuztFZ3LGiCusG5d0/Jz9P+WubB0hFw3Afi50jNIttacZWYKxrDn7ho9GxyUGLmY4WlCt1kVjgM4XrdaPJqNKJX6PXrmNv7FldN/vUahKLeneUZGB0THZ6BLXML0fbjCPPbiW57/+oD9oFTxSkP4pGngfDoFw=="

    # encryptedData = "CvZM2jErg4gmjo89qfP/7ztYUuT9LdcMY5b/Zi8YxsEM9FcqonrpfpKwEuHJOuZh8nSfwJM0zIbSUufpg5ywyeAxne6+l7P8WruwzuaAZJJOVHoQRgyL8OXstEXUyILVaDw8Ki8nEkVqlpdw30l4wR0i7oC1wsHd0Zoy4tfsQ3aEjXKdgkdXTl3pXwlz1xD8A1ekxlpax+jMsZl8fh+Qgg=="
    # iv = "w+n9bKT3VBRGntDhBv7QjQ=="
    # sessionKey = "+zZyZiiG5eq2ZuX+60I6Cg=="

    encryptedData = "YKdktBHJEo8am/Kyeg2CAPyMoVR3xrej0DvJlLlbOFYq+vAgt/LS/Nw7mgOiKjy4O/NPL6sjupri2ke8gDYi7bKa2VdCpGOHILsQ3/pTTbJaLE/6+nMdw4HhRKGGRTogYE3bYnVs4AVakyouuaS3pN2IjWh3Cbs8eYPTafnIYYRa7Ujwb0VgaUsv5F9NsQjC+EA6NPiosGRDRhGX0NTJOA=="
    sessionKey = "4OpuVBNi+EU+I2392k5Eag=="
    iv = "TEMUmTzEUIRKuWYEb/KVsw=="
    pc = WXBizDataCrypt(appId, sessionKey)
    print(pc.decrypt(encryptedData, iv))


if __name__ == '__main__':
    main()
